#include "stdafx.h"
#include <irrlicht.h>
#include "ICustomizableTriangleMeshNode.h"
using namespace irr;
using namespace scene;
using namespace video;
using namespace core;

ICustomizableTriangleMeshNode::ICustomizableTriangleMeshNode(ISceneNode* parent, ISceneManager* mgr, s32 id):ISceneNode(parent, mgr, id){
	Material.Wireframe = false;
	Material.Lighting = false;
	Vertices.clear();
	Indices.clear();
	Box.reset(0,0,0);
}

u16*ICustomizableTriangleMeshNode::getIndices(){
	return Indices.data();
}

s32 ICustomizableTriangleMeshNode::getIndicesCount(){
	return Indices.size();
}

s32 ICustomizableTriangleMeshNode::getVertexCount(){
	return Vertices.size();
}

S3DVertex*ICustomizableTriangleMeshNode::getVertices(){
	return Vertices.data();
}

void ICustomizableTriangleMeshNode::recalculate(){
	if(Vertices.size()==0){
		Box.reset(0,0,0);
	}else{
		Box.reset(Vertices[0].Pos);
		for (u32 i=1; i<Vertices.size(); ++i){
			Box.addInternalPoint(Vertices[i].Pos);
		}
	}
}

void ICustomizableTriangleMeshNode::OnRegisterSceneNode(){
	if (IsVisible && Indices.size()!=0){
		SceneManager->registerNodeForRendering(this);
	}

	ISceneNode::OnRegisterSceneNode();
}

const core::aabbox3d<f32>& ICustomizableTriangleMeshNode::getBoundingBox() const{
	return Box;
}

void ICustomizableTriangleMeshNode::render(){
	if(Vertices.size()==0 || Indices.size()==0){
		return;
	}

	video::IVideoDriver* driver = SceneManager->getVideoDriver();
	driver->setMaterial(Material);
	driver->setTransform(video::ETS_WORLD, AbsoluteTransformation);
	driver->drawVertexPrimitiveList(&Vertices[0], Vertices.size(), &Indices[0], Indices.size()/3, video::EVT_STANDARD, scene::EPT_TRIANGLES, video::EIT_16BIT);
}

video::SMaterial& ICustomizableTriangleMeshNode::getMaterial(u32 i){
	return Material;
}   

u32 ICustomizableTriangleMeshNode::getMaterialCount() const{
	return 1;
}

void ICustomizableTriangleMeshNode::setIndices(u16*indices, int indicesCount){
	Indices.clear();
	for(int i=0;i<indicesCount;i++){
		Indices.push_back(indices[i]);
	}
}


void ICustomizableTriangleMeshNode::setVertices(S3DVertex*vertices, int verticesCount){
	Vertices.clear();
	for(int i=0;i<verticesCount;i++){
		Vertices.push_back(vertices[i]);
	}
}